package com.mz.ieann.aide.widget

import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import java.util.*
import kotlin.math.abs


/**
 * <p>------------------------------------------------------
 * <p> Copyright (C) 2021 zhangmz, All rights reserved.
 * <p> If there is technical discussion, you can contact zhangmz90@foxmail.com
 * <p>------------------------------------------------------
 * <p> des
 * <p>
 *
 * @author Created by zhangmz90
 * @date on 2021 2021/11/14 13:39
 */
class NowrapTextview @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {

    override fun isFocused(): Boolean {
        return true
    }

    /**
     * 配置最大行数
     */
    private var curMaxLine = maxLines

    /**
     * 配置省略号显示位置
     */
    private var ellipsis = ellipsize

    /**
     * 文字
     */
    private val content = text

    /**
     * view可显示字符宽度
     */
    private val w by lazy {
        measuredWidth - paddingStart - paddingEnd
    }

    /**
     * 用来获得固定字符串宽度
     */
    private val fm by lazy { paint.fontMetrics }

    override fun onDraw(canvas: Canvas?) {
        curMaxLine = maxLines
        ellipsis = ellipsize
        when{
            curMaxLine <= 1 || canvas == null -> super.onDraw(canvas)
            else -> drawText(canvas)
        }
    }

    /**
     * 重新绘制文字，未满一行不自动换行
     */
    private fun drawText(canvas: Canvas){
        paint.color = currentTextColor
        paint.textSize = textSize

        var height = paddingTop.toFloat() + abs(fm.top)
        val contentArray: MutableList<String> = ArrayList(curMaxLine)

        var min = 0
        for (i in 1 until content.length){
            if (paint.measureText(content, min, i) >= w) {
                contentArray.add(content.substring(min, i.coerceAtMost(content.length)))
                min = i
                continue
            }
        }
        if (min < content.length){
            contentArray.add(content.substring(min, content.length))
        }
        val length = curMaxLine.coerceAtMost(contentArray.size)
        for (i in 0 until length){
            var content = contentArray[i]
            if (i >= length - 1 && paint.measureText("$content...") >= w) {
                content = "${content.substring(0, content.length - 2)}..."
            }
            canvas.drawText(content, paddingStart.toFloat(), height * lineSpacingMultiplier + lineSpacingExtra, paint)
            height += abs(fm.leading) + abs(fm.ascent) + abs(fm.descent) + abs(fm.bottom)
        }
    }

}